<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Express;
use app\common\library\Pay;
use app\common\model\Cart;
use app\common\model\coupon\Log;
use app\common\model\Express as ModelExpress;
use app\common\model\goods\Goods;
use app\common\model\goods\Review;
use app\common\model\MoneyLog;
use app\common\model\Order as ModelOrder;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\Order as OrderOrder;
use app\common\model\User;
use think\Db;
use think\Log as ThinkLog;
use think\Queue;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = ['*'];
    /**
     * 订单预下单
     *
     */
    public function yuOrder()
    {
        $get = request()->get();
        $uid =  $this->auth->id;
        extract($get);
        if (!isset($ids) || empty($ids)) {
            $this->error('参数错误');
        }
        if ($distribution == '2') {
            if (!isset($shop_id) || empty($shop_id)) {
                $this->error('请选择自提点');
            }
        }
        $goods = Cart::getGoods($ids, $uid);
        $order = new OrderOrder();
        $data = [
            'distribution' => $distribution,
            'goods' => $goods,
            'coupon_id' => $coupon_id ?? 0,
            'address_id' => $address_id ?? 0,
            'uid' => $uid,
            'shop_id' => $shop_id ?? 0,
        ];
        $data = $order->yuOrder($data);
        if (is_array($data)) {
            $this->success('', $data);
        }
        $this->error($data);
    }
    /**
     * 订单统一下单
     *
     */
    public function addOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $uid = $this->auth->id;
        $data = cache('order_' . $uid);
        extract($data);
        if (!$data) {
            $this->error('订单已失效，请重新选择商品');
        }
        if ($distribution == '1') {
            $msg = '收货地址不能为空';
        } else {
            $msg = '取货信息不能为空';
        }
        if (!isset($address_id) || empty($address_id)) {
            $this->error($msg);
        }
        Db::startTrans();
        try {
            //添加订单商品信息
            $order = new OrderOrder();
            $order_id = $order->addData($data, $uid);
            if (!$order_id) {
                exception('下单失败');
            }
            Log::where('id', $coupon_id)->update(['state' => 2]);
            $total_order = OrderOrder::get($order_id);
            $goods = OrderGoods::where('order_id', $order_id)->column('goods_id,goods_num');
            foreach ($goods as $key => $v) {
                Goods::reduceInventory($key, $v);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return self::error($e->getMessage() );
        }
        // Queue::later(900, 'app\common\job\Order', $total_order, 'order');
        queue('app\common\job\Order', $total_order, 900, 'order');
        cache('order_' . $uid, null);
        return $this->success('下单成功', $order_id);
    }

    /**
     * 立即付款
     *
     */
    public function pay()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        $userInfo = $this->auth->getUser();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        if (!isset($pay_type)) {
            $this->error('请选择支付方式');
        }
        try {
            $order = OrderOrder::get($id);
            if ($userInfo->group_id != 1) {
                $order->p_id = 0;
                $order->p_interests = 0;
            }
            if ($order['pay_money'] <= 0) {
                $order->status = 1;
                $order->paytime = time();
                $code = 200;
                $sdk = '';
            } else {
                if ($pay_type == '0') {
                    $sdk = Pay::wxpay($order, 'order');
                    //微信支付
                } elseif ($pay_type == '1') {
                    //支付宝支付
                    $sdk = Pay::alipay($order);
                } elseif ($pay_type == '2') {
                    //余额支付
                    $sdk =  Pay::yue($order, $payPwd);
                } elseif ($pay_type == '3') {
                    //微信小程序支付
                    // $user = User::get($order->user_id);
                    $sdk = Pay::minipay($order, $openid, 'order');
                }
            }
            //更换支付方式
            $order->pay_type = $pay_type;
            $order->save();
        } catch (\Exception $e) {
            ThinkLog::write('提交支付失败：' . $e->getMessage());
            $this->error('提交支付失败：' . $e->getMessage());
        }
        $this->success('', $sdk, $code ?? 1);
    }

    /**
     * 我的订单
     *
     */

    public function list()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        if ($type != 'all') {
            $where['status'] = ['=', $type];
        }
        $where['user_id'] = ['=',  $this->auth->id];
        $order = OrderOrder::with('goods')->where($where)->where('status', '<>', '-1')->order('createtime desc')->paginate(10);
        $this->success('获取成功', $order);
    }

    /**
     * 订单详情
     *
     */
    public function info()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $info = OrderOrder::get($id, ['goods', 'shop']);
        $this->success('获取成功', $info);
    }
    /**
     * 查看物流
     *
     */
    public function logistics()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        $express = new Express($order);
        $wuliu = $express->getOrderTracesByJson();
        $wuliu['express_name'] = ModelExpress::where('customer', $order['express_com'])->value('name');
        $wuliu['address'] = $order['address'];
        $wuliu['city'] = $order['city'];
        $wuliu['nu'] = $order['express_no'];
        $this->success('', $wuliu);
    }

    /**
     * 取消订单
     *
     */
    public function cancelOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id);
        if ($order['status'] != 0) {
            $this->error('订单状态错误');
        }
        $res = $order->save(['status' => '-1', 'deletetime' => time()]);
        if ($res) {
            $this->success('取消成功');
        }
        $this->error('取消失败');
    }
    /**
     * 申请退货/退款
     *
     */
    public function returnOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id);
        if (!in_array($order['status'], ['1', '2'])) {
            $this->error('订单状态错误');
        }
        $res = $order->save(['status' => '5']);
        if ($res) {
            $this->success('申请成功');
        }
        $this->error('申请失败');
    }
    /**
     * 删除订单
     *
     */
    public function deleteOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }

        $res = OrderOrder::get($id);
        $res = $res->delete();
        if ($res) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
    /**
     * 确认订单
     *
     */
    public function confirmOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $order = OrderOrder::get($id);
            if (!$order) {
                exception('订单不存在');
            }
            if ($order->status != 2) {
                exception('订单状态错误');
            }
            $order->save(['status' => 3,'taketime' => time()], ['id' => $id]);
            $money = $order->pay_money - $order->freight;
            //订单分佣
            MoneyLog::subcommission($money, $order->user_id, $order->sn);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error('操作失败：' . $th->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * 订单评论
     *
     */
    public function comment()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($order_id) || empty($order_id)) {
            $this->error('参数错误');
        }
        if (!isset($data) || empty($data)) {
            $this->error('提交错误');
        }
        $Review = new Review();
        $res = $Review->addReview($post, $this->auth->id);
        if ($res === true) {
            $this->success('评论成功');
        }
        $this->error('评论失败:' . $res);
    }
    /**
     * 再来一单
     *
     */
    public function moreOrder()
    {
        $get = request()->param();
        $uid =  $this->auth->id;
        extract($get);

        $goods = Cart::getProducts($goods_id, $uid, $num);
        $order = OrderOrder::with(['goods' => function ($q) use ($goods) {
            $q->where('goods_id', $goods->id);
        }])->where('user_id', $uid)->where('status', '>', '0')->find();
        if (!$goods) {
            $this->error('商品不存在');
        }
        if ($goods->stock < $num) {
            $this->error('库存不足');
        }
        if ($goods->state == '1' && $goods->category_id == 17 && ($num > 1 || $order)) {
            $this->error('爆款商品限购1个');
        }
        if ($goods->status == '0') {
            $this->error('商品【' . $goods->title . '】已下架，不能下单');
        }
        if ($goods->deletetime != null) {
            $this->error('商品【' . $goods->title . '】已删除，不能下单');
        }
        if ($distribution == '2') {
            if (!isset($shop_id) || empty($shop_id)) {
                $this->error('请选择自提点');
            }
        }
        try {
            $order = new OrderOrder();
            $data = [
                'distribution' => $distribution,
                'goods' => $goods,
                'num' => $num,
                'coupon_id' => $coupon_id ?? 0,
                'address_id' => $address_id ?? 0,
                'uid' => $uid,
                'shop_id' => $shop_id ?? 0,
            ];
            $data = $order->moreOrder($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if (is_array($data)) {
            cache('order_' . $uid, $data, '900');
            $this->success('', $data);
        }
    }
}
